package control
{
	import flash.events.Event;
	import flash.net.URLVariables;
	
	import model.ModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import view.msg;
	public class dbMsg
	{
		private var msgCopy:msg;
		internal var theModel:ModelLocator = ModelLocator.getInstance();
		private var saveMsgHttp:HTTPService;
		private var delMsgHttp:HTTPService;
		private var modMsgHttp:HTTPService;
		public function dbMsg(m1:msg)
		{
			msgCopy=m1;
			saveMsgHttp = new HTTPService();
			saveMsgHttp.url = "http://localhost:8080/GMdb/servlet/saveMsg";
			saveMsgHttp.addEventListener(ResultEvent.RESULT,saveMsgHandler);
			saveMsgHttp.addEventListener(FaultEvent.FAULT, fHandler);
			delMsgHttp = new HTTPService();
			delMsgHttp.url = "http://localhost:8080/GMdb/servlet/delMsg";
			delMsgHttp.addEventListener(ResultEvent.RESULT,delMsgHandler);
			delMsgHttp.addEventListener(FaultEvent.FAULT, fHandler);
			modMsgHttp = new HTTPService();
			modMsgHttp.url = "http://localhost:8080/GMdb/servlet/modMsg";
			modMsgHttp.addEventListener(ResultEvent.RESULT,modMsgHandler);
			modMsgHttp.addEventListener(FaultEvent.FAULT, fHandler);
		}
		public function saveMsg(pathid:int,username:String,msg:String):void
		{
			var params:URLVariables = new URLVariables();
			params.pathid=pathid;
			params.username=httpEncoding(username);
			params.msg=msg;
			
			saveMsgHttp.method="POST";
			saveMsgHttp.send(params);
		}
		public function deleteMsg(msgid:int):void{
			var params:URLVariables = new URLVariables();
			
			params.msgid=msgid;
			delMsgHttp.send(params);
		}
		public function modifyMsg(msgid:int,message:String):void{
			
			var params:URLVariables = new URLVariables();
			params.msgid=msgid;
			params.message=message;
			//Alert.show(message);
			modMsgHttp.send(params);
			
		}
		private function httpEncoding(param:String):String{
                return encodeURIComponent(param);
        }
		internal function saveMsgHandler(event:ResultEvent):void{
			//(msgCopy.allMessages as ArrayCollection).addItem(event.result.msg);
       		theModel.dispatchEvent(new Event(ModelLocator.SAVE_MSG_OK));
       	}
       	internal function delMsgHandler(event:ResultEvent):void{
       		
       	}
       	internal function modMsgHandler(event:ResultEvent):void{
       		theModel.dispatchEvent(new Event(ModelLocator.MOD_MSG_OK));
       	}
		internal function fHandler (event:FaultEvent):void {
         		Alert.show(event.fault.message,"Error1")
        }
	}
}